package filters

import (
	"boomlive.com/boomlive-common/configs"
	"boomlive.com/boomlive-common/constants"
	"boomlive.com/boomlive-common/utils"
	"github.com/beego/beego/v2/core/logs"
	beecontext "github.com/beego/beego/v2/server/web/context"
)

var AllowIps []string

func init() {
	AllowIps = configs.FilterIpAllowIps
}

func FilterIp(ctx *beecontext.Context) {
	isOpen := configs.FilterIpOpen

	if isOpen == 0 {
		return
	}

	if len(AllowIps) == 0 {
		return
	}

	clientIp := ctx.Input.IP()

	if clientIp == "" {
		logs.Error("clientIp is empty requestId=%s", ctx.Input.GetData("requestId"))
		ipValidateFail(ctx)
		return
	}

	if !utils.InSlice(AllowIps, clientIp) && !utils.InSlice(AllowIps, "*") {
		logs.Error("clientIp is not allowed, clientIp=%s requestId=%s", clientIp, ctx.Input.GetData("requestId"))
		ipValidateFail(ctx)
		return
	}
}

func ipValidateFail(ctx *beecontext.Context) {
	res := utils.GenerateResultBody(constants.ERR_IP_SOURCE, nil, utils.GetLanguageCode(ctx))
	_ = ctx.Output.JSON(res, false, false)
}
